<?php
namespace Home\Controller;

use Home\Model\CartsModel;
use Think\Controller;
use Home\Model\GoodsModel;
use Think\Model;

class GoodsController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->local_id = I('local_id', '', 'intval') ?: session('userInfo')['local_id'];
    }

    /**
     * 查看商品详情
     */
    public function detail()
    {

        $m = new GoodsModel();
        $pdetail = $m->getbydetail(I('get.id'));
        if (empty($pdetail['name'])) {
            $this->redirect('goods/error404');
        }
        //查询是否已关注该商品
        if($member_id = session('userInfo')['member_id']){
            $local_id = I('get.local_id');
            $productLike = M('b2c_member_like')->where(['product_id'=>$pdetail['product_id'],'member_id'=>$member_id,'local_id'=>$local_id,'status'=>1])->find();

            $this->assign('productLike',$productLike);
        }
        $plist = $m->getproduct(I('get.id'));
        $car_num =  $m->getcartnum();
        $pid =I('get.id');
        $this->assign('id', $pid);
        $local_id = $this->local_id;
        $storeData = M('webpos_local_store')->where(['local_id'=>$local_id])->find();
        if ($storeData['services']) {
            $storeData['services'] = json_decode($storeData['services'], true);
        }

        $group_list = $this->groupGoodslist($pid);
        //获取商品的相册
        if ($pdetail['goods_id']) {
            $phones = $m->getGoodsPhotos($pdetail['goods_id']);
            $this->assign('phones', $phones);
        }

        /**
        *判断货品是否是闪购产品
        promotion_price ini_y_tnum initnum repertory_num countnum limit begin_time end_time
        6.000               0       6           0           0       1   1477864800 1477872000
         */
        $flashGoods = $m->checkGoodsIsStarBuy($pid);
        //print_r($flashGoods);
        $this->assign('flashGoods', $flashGoods);

        /**
         * 判断商品是否是促销产品
         * @author 黄
         * @parameter $id  商品id
         * @parameter $$local_id  门店id
         */
        $proPrice = $m->checkGoodsIsPromotion($local_id, $pid);
        $this->assign('proPrice', $proPrice);

        //获取用户评论
        $comments = $m->getStoreProductComments(I('get.id'), 1, 12);
        $this->assign('comments', $comments);
        //查询当前货品在购物车中的个数
        $default_num = $m->getDetailNumInCart($pdetail['local_id'], $pdetail['product_id']);
        $this->assign('default_num', $default_num);
        //查询商品的标签
        $tags = $m->getProductTags($pdetail['local_id'], $pdetail['product_id']);
        $this->assign('tags', $tags);
        if(!empty($pdetail)){

            $this->assign('plist', $plist);
            $this->assign('pdetail', $pdetail);
            $this->assign('cnum', $car_num);
        }

        //购物车情况
        $mCart = new CartsModel();
        $cartLast =   $mCart->getCartData($member_id);
        $total_goods_money = 0;
        foreach ($cartLast as $k=>$value){
            $total_goods_money += $value['lp_fee'];
        }
        $total_goods_money = number_format($total_goods_money, 2, '.', '');
        $group_len = count($group_list);
        $this->assign('storeData',$storeData);
        $this->assign('CartMoney',$total_goods_money);
        $this->assign('group_len', $group_len);
        $this->assign('group_product', $group_list[0]);
        //$this->assign('diff_price', $group_product['diff_price']);
        $this->display('Goods/product');

    }

    /**
     * 组合商品列表页面
     */
    public function groupGoods() {
        //店铺的product_id
        $id = I('id', 0, 'intval');
        if (!$id) $this->error('走错了');

        $list = $this->groupGoodslist($id);
        $this->assign('list', $list);
        $this->display();
    }

    /** 获取正在进行的组合促销列表
     * @param $id
     * @return array
     */
    public function groupGoodslist($id) {
        $data = M()->cache(true, 120)->query($this->_diy_sql($id));
        $list = [];
        $aa = [];
        $sum=0;
        $j=1;
        if (!empty($data) && is_array($data)) {
            foreach ($data as $k=>$item) {
                $list[$item['id']]['id'] = $item['id'];
                $list[$item['id']]['local_id'] = $item['local_id'];
                $list[$item['id']]['name'] = $item['name'];
                $list[$item['id']]['total_price'] = $item['total_price'];
                $list[$item['id']]['total_weight'] = $item['total_weight'];
                $list[$item['id']]['state'] = $item['state'];
                $list[$item['id']]['start_time'] = $item['start_time'];
                $list[$item['id']]['end_time'] = $item['end_time'];
                $list[$item['id']]['list'] = [];
                $ii = [
                    'item_id' => $item['item_id'],
                    'sp_id' => $item['sp_id'],
                    'local_id' => $item['local_id'],
                    'product_id' => $item['product_id'],
                    'goods_id' => $item['goods_id'],
                    'num' => $item['num'],
                    'price' => $item['price'],
                    'marketprice' => $item['marketprice'],
                    'store' => $item['store'],
                    'store_status' => $item['store_status'],
                    'freez' => $item['freez'],
                    'pname' => $item['pname'],
                    'spec_info' => $item['spec_info'],
                ];
                $aa[$item['id']][] = $ii;
                $list[$item['id']]['list'] = $aa[$item['id']];
            }
            sort($list);
            foreach ($list as $key => &$item) {
                $count = count($item['list']);
                if ($count > 0) {
                    $product_status = array_column($item['list'], 'store_status');
                    // false 下架 排除
                    if (in_array('false', $product_status)) {
                        unset($list[$key]);
                        continue;
                    }
                    $temp = 0;
                    foreach ($item['list'] as $p) {
                        $temp += $p['price'] * $p['num'];
                    }
                    $item['sheng'] = bcsub($temp, (float)$item['total_price'], 2);
                    //判断库存
                    foreach ($item['list'] as $v) {

                        if ($v['store'] - $v['freez'] < $v['num']) {
                            $item['sale_status'] = false;
                            break;
                        } else {
                            $item['sale_status'] = true;
                        }
                    }
                }
            }
        }
        return $list;
    }

    public function _diy_sql($sp_id) {
        /**
        select a.*,b.*,c.price,c.marketprice,c.store,d.`name`as pname from sdb_b2c_store_promotion_group a
        LEFT JOIN sdb_b2c_store_promotion_group_item b on a.id=b.group_id
        LEFT JOIN sdb_b2c_store_product c on b.sp_id=c.store_pid
        LEFT JOIN sdb_b2c_products d on b.product_id=d.product_id
        where a.id in (
        SELECT `group_id` FROM `sdb_b2c_store_promotion_group_item` where sp_id=55
        )
         */
        $now = time();
        $sql = "select a.*,b.id as item_id,b.sp_id,b.product_id,b.goods_id,b.num,c.price,c.freez,c.marketprice,c.store,c.store_status,d.`name`as pname,d.`spec_info` from ".C('DB_PREFIX')."b2c_store_promotion_group a";
        $sql .=" LEFT JOIN ".C('DB_PREFIX')."b2c_store_promotion_group_item b on a.id=b.group_id";
        $sql .=" LEFT JOIN ".C('DB_PREFIX')."b2c_store_product c on b.sp_id=c.store_pid";
        $sql .=" LEFT JOIN ".C('DB_PREFIX')."b2c_products d on b.product_id=d.product_id";
        $sql .=" where a.id in (";
        $sql .="SELECT `group_id` FROM ".C('DB_PREFIX')."b2c_store_promotion_group_item where sp_id={$sp_id}";
        $sql .=") and a.state='1' and a.start_time <={$now} and a.end_time>={$now}";
        return $sql;
    }

    /**
     *
     */


    public function addGroupCart(){
        $data = $_POST;

        if(empty(session('userInfo')['member_id'])){
            $this->ajaxReturn(array('status'=>0,'url'=>url('Login/index'),'msg'=>'还未登录，请登录！'));
        }

        //购物车  是否有其他商品，获取该商品的 shipping
        $shipP = M('b2c_carts')->where(['local_id'=>$data['local_id']])->field('shipping')->find();

        if(!empty($shipP)){
            $data['shipping'] = $shipP['shipping'];
        }else{
            $data['shipping'] = 1;
        }

        //商品是否存在
       $isAdd = M('b2c_carts')->where(['group_id'=>$data['group_id'],'member_id'=>session('userInfo')['member_id'],'type'=>1])->find();

       if(!empty($isAdd)){
           //判断库存

          $group_goods =  M('b2c_store_promotion_group_item gi')
               ->join('left join sdb_b2c_store_product sp on sp.store_pid = gi.sp_id')
               ->where(['group_id'=>$data['group_id']])
               ->field('gi.num,gi.sp_id,gi.product_id,gi.num,sp.store,sp.freez,sp.p_name')
               ->select();
           // print_r($group_goods);
          foreach ($group_goods as $k=>$val){

              $res = $this->group_is_enough($val['product_id'],$data['local_id'],session('userInfo')['member_id'],$val['num'],$data['group_id'],$val['store'],$val['freez'],$val['p_name']);

              if($res['status']==0){
                  $this->ajaxReturn(array('status'=>0,'msg'=>$res['msg']));
                  break;
              }
          }


           //存在
           $newCartNum= $isAdd['cart_num'] +1;
           $result = M('b2c_carts')->where(['id'=>$isAdd['id']])->save(array('cart_num'=>$newCartNum,'shipping'=>$data['shipping']));
           if($result){
               $this->ajaxReturn(array('status'=>1,'msg'=>'添加套餐成功','url'=>url('Carts/cart')));
           }
       }else{
           $cartData['member_id'] = session('userInfo')['member_id'];
           $cartData['cart_num'] = 1;
           $cartData['ischeck'] = 1;
           $cartData['time'] = time();
           $cartData['shipping'] = $data['shipping'];
           $cartData['type'] = 1;
           $cartData['local_id'] = $data['local_id'];
           $cartData['group_id'] = $data['group_id'];

           $result = M('b2c_carts')->add($cartData);

           if($result){
               $this->ajaxReturn(array('status'=>1,'msg'=>'添加套餐成功','url'=>url('Carts/cart')));
           }
       }

        $this->ajaxReturn(array('status'=>0,'msg'=>'添加失败'));
    }
    public function group_is_enough($pid,$lid,$mid,$num,$group_id,$store,$freez,$pname){
        //echo $store.'|'.$freez.'|';
        //该用户该商品购物车存在数量
        $cartStore = M('b2c_carts c')
            ->join('left join sdb_b2c_store_product sp on sp.product_id = c.product_id and sp.local_id = c.local_id')
            ->where("sp.product_id=$pid and sp.local_id = $lid and c.member_id = $mid")
            ->field("sp.store,sp.freez,c.cart_num,sp.p_name")
            ->find();


        //组合商品数量
        $gnum = M('b2c_carts')->where(['group_id'=>$group_id])->find()['cart_num'];

        //加入数量+购物车数量 < 库存
        //单商品+group单商品数量*group购买量 < (库存-冻结库存)
        //echo $cartStore['cart_num'].'|'.$num*$gnum.'|';
        $totalNum = $cartStore['cart_num'] + $num*$gnum;

        if($totalNum>=($store-$freez)){
            return array('msg'=>$pname.'库存不足','status'=>0);
        }else{
            return array('msg'=>'库存足够','status'=>1);
        }

    }

    /**
     * 评价更多
     */
    public function getMoreComment() {
        $store_pid = I('id', 0, 'intval');
        if (!$store_pid) $this->error404();
        if (!IS_AJAX) {
            $url = url('Home/Goods/getMoreComment',['id'=>$store_pid], '');
            $this->assign('url', $url);
            $this->display();
        } else {

            $p = max(2, I('p', 0, 'intval'));
            $page = max(8, I('page', 0, 'intval'));
            $model = new GoodsModel();
            $list = $model->getStoreProductComments($store_pid, $p , $page);
            $this->ajaxReturn([
                'status' => true,
                'message' => '获取成功',
                'data' => $list
            ]);
        }
    }

    /**
     * 商品详细情况
     */
    public function getGoodsContent() {
        $store_pid = I('id', 0, 'intval');
        if (!$store_pid) {
            $this->ajaxReturn([
                'status' => false,
                'data' => []
            ]);
        }
        $content = M('b2c_store_product')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_goods b on a.goods_id=b.goods_id', 'LEFT')
            ->cache(true,86400, 'redis')
            ->where(['a.store_pid' => $store_pid])
            ->getField('intro');
        $this->ajaxReturn([
            'status' => true,
            'data' => $content
        ]);
    }

    public function error404() {
        $this->show('<h1>404, 没有找到这个页面</h1>');
    }

    public function test() {
        checkProductIsGroupPromotion(I('id'));
    }
}